#include <winsock2.h>
#include <burst_kernel.h> 

static void __stdcall bus_console_mouse_reader_thread()
{
	int i;
	uint32_t ev_read;
	INPUT_RECORD input_buf[512];
	HANDLE read_fd = GetStdHandle(STD_INPUT_HANDLE);
	HANDLE write_fd = GetStdHandle(STD_OUTPUT_HANDLE);
	while(1) {
		memset(input_buf, NULL, sizeof(INPUT_RECORD) * 512);
		ReadConsoleInput(read_fd, input_buf, 512, &ev_read);
		for(i = 0;i < ev_read;i++) {
			if(input_buf[i].Event.MouseEvent.dwButtonState & FROM_LEFT_1ST_BUTTON_PRESSED) {
				/* bus_debug_print("Mouse left key clicked at \(%d, %d\)\n", input_buf[i].Event.MouseEvent.dwMousePosition.X, input_buf[i].Event.MouseEvent.dwMousePosition.Y); */
			}
			if(input_buf[i].Event.MouseEvent.dwButtonState & RIGHTMOST_BUTTON_PRESSED) {
				/* bus_debug_print("Mouse right key clicked at \(%d, %d\)\n", input_buf[i].Event.MouseEvent.dwMousePosition.X, input_buf[i].Event.MouseEvent.dwMousePosition.Y); */
			}
		}
	}
}

void bus_system_init()
{
	CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)&bus_console_mouse_reader_thread, NULL, NULL, NULL);
}

void bus_module_load_all(char *dirpath)
{
	HANDLE find_fd;
	WIN32_FIND_DATAA wfd;
	char path[256]; 
	strcpy(path, dirpath);  
	strcat(path, "\\*.dll");

	find_fd = FindFirstFile(path, &wfd);
	if (find_fd != INVALID_HANDLE_VALUE) {  
		while (FindNextFile(find_fd, &wfd)) {
			if (wfd.cFileName[0] == '.')continue;  
			if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
				strcpy(path, dirpath);
				strcat(path, "\\");  
				strcat(path, wfd.cFileName);  
				bus_module_load_all(path);
			} else {
				char tmp_path[256];
				HMODULE dll_fd;
				bus_debug_print("Find module: %s\n", wfd.cFileName);
				strcpy(tmp_path, dirpath);
				strcat(tmp_path, "\\");
				strcat(tmp_path, wfd.cFileName);
				dll_fd = LoadLibrary(tmp_path);
				if(!dll_fd) {
					continue;
				}
				{
					bus_module_t *mod_ptr;
					bus_module_init_t *init;
					init = (bus_module_init_t *)GetProcAddress(dll_fd, "bus_module_init");
					if(!init) {
						bus_debug_print("%s is not a module of Bus.Skipped.\n", wfd.cFileName);
						continue;
					}
					mod_ptr = init(&bus_kernel);
					bus_module_insert(mod_ptr);
				}
			}
		}  
	}
}